import {
  IsNotEmpty,
  Length,
  ValidationOptions,
  ValidationArguments,
  registerDecorator,
} from "class-validator";

function IsSameValue(property: string, validationOptions?: ValidationOptions) {
  return function (target: Object, propertyName: string) {
    registerDecorator({
      name: "isSameValue",
      target: target.constructor,
      propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        validate(
          value: any,
          validationArguments?: ValidationArguments
        ): Promise<boolean> | boolean {
          // 第一个参数指定的属性对应的值
          const relatedValue =
            validationArguments &&
            (validationArguments.object as any)[property];

          // value: 当前被装饰的值
          return relatedValue === value;
        },
      },
    });
  };
}

//  基类, 因为登录和注册都需要验证名字和密码
class UserBody {
  @Length(1, 50, {
    message: "用户名不能为空或者大于50个字符",
  })
  name: string;

  @IsNotEmpty({
    message: "密码不能为空",
  })
  password: string;
}

export class RegesiterBody extends UserBody {
  //  自定义的装饰器, 验证两次输入的密码是否一致
  @IsSameValue("password", {
    message: "两次输入的密码不一致",
  })
  rePassword: string;
}

export class LoginBody extends UserBody {}
